package com.fyales.android.juhejoke.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.fyales.android.api.ApiClient;
import com.fyales.android.api.callback.HttpRequestCallBack;
import com.fyales.android.api.constant.HttpConstants;
import com.fyales.android.api.model.Data;
import com.fyales.android.api.model.Joke;
import com.fyales.android.component.PullToRefreshLayout;
import com.fyales.android.juhejoke.R;
import com.fyales.android.juhejoke.adapter.TextJokeAdapter;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import rx.Observable;
import rx.Subscriber;
import rx.functions.Action1;


public class MainActivity extends AppCompatActivity implements PullToRefreshLayout.ActionListener, SwipeRefreshLayout.OnRefreshListener {

    @Bind(R.id.refresh_lv)
    PullToRefreshLayout refreshLv;
    @Bind(R.id.ad_container)
    RelativeLayout adContainer;

    public static final boolean STATE_LOAD_MORE = false;
    public static final boolean STATE_REFRESH = true;
    private List<Joke> jokeList;
    private TextJokeAdapter adapter;
    private boolean state;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setTitle("笑林");
        ButterKnife.bind(this);

        initAd();

        state = STATE_LOAD_MORE;

        jokeList = new ArrayList<>();
        adapter = new TextJokeAdapter(this, jokeList);
        refreshLv.setAdapter(adapter);
        refreshLv.setRefreshAndLoadMoreListener(this);
        refreshLv.setOnRefreshListener(this);
        refreshLv.setColorSchemeColors(
                getResources().getColor(R.color.primary)
        );
        getJokeList(HttpConstants.SORT_DESC, System.currentTimeMillis() / 1000 + "");
    }

    @Override
    protected void onResume() {
        super.onResume();
        //Observer 与 Observable的例子。
        Subscriber<String> subscriber = new Subscriber<String>() {
            @Override
            public void onStart() {
                super.onStart();
                Log.d("weiweishen","好，开始报数!");
            }

            @Override
            public void onCompleted() {
                Log.d("weiweishen","好，解散!");
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(String s) {
                Log.d("weiweishen",s);
            }
        };

        Observable<String> observable = Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                subscriber.onNext("一个老鼠");
                subscriber.onNext("三只狐狸");
                subscriber.onNext("两头牛");
                subscriber.onCompleted();
            }
        });
        //替代方案
//        Observable observable = Observable.just("一个老鼠", "三只狐狸", "两头牛");
//         onNext("Hello");
//         onNext("Hi");
//         onNext("Aloha");
//         onCompleted();

//        String[] words = {"Hello", "Hi", "Aloha"};
//        Observable observable = Observable.from(words);
//          onNext("一个老鼠");
//          onNext("三只狐狸");
//          onNext("两头牛");
//          onCompleted();

        //ActionX的例子
        Action1<String> onNextAction = new Action1<String>() {
            @Override
            public void call(String s) {
                Log.d("weiweishen","From onNextAction");
            }
        };


        observable.subscribe(onNextAction);
        observable.subscribe(subscriber);

        addBooks(new ArrayList<>());


    }

    private void addBooks(List<Object> list){
        list.add(1);
        list.add("one");
    }

    private void getJokeList(String sort, String time) {

        ApiClient.commonService.getJokes(sort, 1, 20, time).enqueue(new HttpRequestCallBack<Data>() {
            @Override
            public void onSuccess(Data ret) {
                if (state) {
                    refreshLv.setRefreshing(false);
                    jokeList.clear();
                } else {
                    refreshLv.loadFinished();
                }
                if (ret != null && ret.getData() != null && ret.getData().size() != 0) {
                    jokeList.addAll(ret.getData());
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onError(String errorCode, String errorMsg) {
                if (state) {
                    refreshLv.setRefreshing(false);
                } else {
                    refreshLv.loadFinished();
                }
                Toast.makeText(MainActivity.this, "The errorMsg is " + errorMsg, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(String errorMsg) {
                if (state) {
                    refreshLv.setRefreshing(false);
                } else {
                    refreshLv.loadFinished();
                }
                Toast.makeText(MainActivity.this, "The errorMsg is " + errorMsg, Toast.LENGTH_SHORT).show();
            }
        });


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.action_demo) {
            startActivity(new Intent(this,DemoActivity.class));
        }

        return super.onOptionsItemSelected(item);
    }


    @Override
    public void itemClick(int position) {

    }

    @Override
    public void loadMore() {
        state = STATE_LOAD_MORE;
        if (jokeList != null) {
            if (jokeList.size() != 0) {
                getJokeList(HttpConstants.SORT_DESC, jokeList.get(jokeList.size() - 1).getUnixtime() + "");
            } else {
                getJokeList(HttpConstants.SORT_DESC, System.currentTimeMillis() / 1000 + "");
            }
        }
    }

    @Override
    public void onRefresh() {
        state = STATE_REFRESH;
        getJokeList(HttpConstants.SORT_DESC, System.currentTimeMillis() / 1000 + "");
    }

    /**
     * 初始化广告
     */
    private void initAd() {


    }

    @Override
    public void onStart() {
        super.onStart();

    }

    @Override
    public void onStop() {
        super.onStop();


    }
}
